var DZonline = process.env.NODE_ENV == "production";
var loginUrl="/login" 
var ZN = {
    ajax:{
        post: function(params){
        var xmlhttp = this.createXMLHttpRequest();
        if (xmlhttp != null)
        {
            var async = true;
            if (typeof params.async != "undefined")
                async = params.async;
            var data = null;
            if (typeof params.data != "undefined")
                data = params.data;
            var url = "";
            if (typeof params.url != "undefined")
                url = params.url;
            if (url == null || url.length == 0)
                return;
            xmlhttp.open("POST", url, async);
            if (async){
                xmlhttp.onreadystatechange = function(){
                    if (this.readyState==4){
                        if (this.status==200){
                            if (typeof params.success != "undefined") {
                                 if(JSON.parse(xmlhttp.responseText).error==1){
                                     //window.location.href=loginUrl
                                     if(DZonline){
                                        //window.location.href=loginUrl
                                     }
                                 }
                                params.success(JSON.parse(xmlhttp.responseText));
                            }
                        }
                        else {
                            if (typeof params.error != "undefined") {
                                params.error(xmlhttp.status + xmlhttp.statusText);
                            }
                            console.error(url + ": " + xmlhttp.status);
                        }
                    }
                };
            } 
             
            xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            var param = "";
            for (var prop in data) {
                param += prop + "=" + data[prop] + "&";
            }
            param = param.substring(0, param.length - 1);

            //添加csrf校验参数
            var def_wt = ZN.cookie.get("def_wt");
            if (def_wt) {
                param += "&def_wt=" + def_wt
            }

             if(!DZonline){
                if(typeof params.withCredentials=="undefined"){
                    xmlhttp.withCredentials = true;
                }
                else
                {
                    xmlhttp.withCredentials = false; 
                }
            }
            xmlhttp.send(param);
            if (!async) {
                 
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
                    if (JSON.parse(xmlhttp.responseText).error == 1) {
                        //window.location.href=loginUrl
                        if(DZonline){
                          //window.location.href=loginUrl
                        }
                    }
                    if (typeof params.success != "undefined") {
                        params.success(JSON.parse(xmlhttp.responseText));
                    }
                }
                else {
                    if (typeof params.error != "undefined") {
                        params.error(xmlhttp.status + xmlhttp.statusText);
                    }
                    console.error(url + ": " + xmlhttp.status);
                }
                 
            }
        }
    },
    get: function(params){
        var xmlhttp = this.createXMLHttpRequest();
        if (xmlhttp != null)
        {
            var async = true;
            if (params.async != undefined)
                async = params.async;
            var url = "";
            if (params.url != undefined)
                url = params.url;
            if (url == null || url.length == 0)
                return;
            if (params.data != null) {
                var data = params.data;
                var paramPrefix = url.indexOf("?") == -1 ? "?" : "&";
         
                url = url + paramPrefix;
                for (var prop in data) {
                    url += prop + "=" + data[prop] + "&";
                }
                url = url.substring(0, url.length - 1);
            }

            //添加csrf校验参数
            var def_wt = ZN.cookie.get("def_wt");
            if (def_wt) {
                if (url.indexOf("?") > -1) {
                    url += "&def_wt=" + def_wt
                } else {
                    url += "?def_wt=" + def_wt
                }
            }

            xmlhttp.open("GET", url, async);
            if (async){
                xmlhttp.onreadystatechange = function(){
                    if (this.readyState==4){
                        if (this.status==200){
                            if (typeof params.success != "undefined") {
                               if(JSON.parse(xmlhttp.responseText).error==1){
                                    //window.location.href=loginUrl
                                    if(DZonline){
                                          //window.location.href=loginUrl
                                    }
                               }
                               params.success(JSON.parse(xmlhttp.responseText));
                            }
                        }
                        else {
                            if (typeof params.error != "undefined") {
                                params.error(xmlhttp.status + xmlhttp.statusText);
                            }
                            console.error(url + ": " + xmlhttp.status);
                        }
                    }
                };
            }
            if(!DZonline){
                if(typeof params.withCredentials=="undefined"){
                    xmlhttp.withCredentials = true;
                }
                else
                {
                    xmlhttp.withCredentials = false; 
                }
            }
            xmlhttp.send(null);
            if (!async) {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
                    if (typeof params.success != "undefined") {
                        if(JSON.parse(xmlhttp.responseText).error==1){
                              //window.location.href=loginUrl
                            if(DZonline){
                              //window.location.href=loginUrl
                            }
                        }
                        params.success(JSON.parse(xmlhttp.responseText));
                    }
                else {
                    if (typeof params.error != "undefined") {
                        params.error(xmlhttp.status + xmlhttp.statusText);
                    }
                    console.error(url + ": " + xmlhttp.status);
                }
                         
                 
            }
        }
    },
    createXMLHttpRequest: function(){
        if (window.XMLHttpRequest)
        {
            return new XMLHttpRequest();
        }
        else if (window.ActiveXObject)
        {
        //code for IE5 and IE6
            return new ActiveXObject("Microsoft.XMLHTTP");
        }
        return null;
    },
    getJSONP: function(params) {
        var url = null;
        if (typeof params.url != "undefined") {
            url = params.url;
        }
        if (url == null) {
            return;
        }
         
        var ff = "" + new Date().getTime() + (parseInt(Math.random() * 10000000000));
        eval("jsonpCallback_" + ff + "=" + function(data){
     
            if (typeof params.success != "undefined") {
                params.success(data);
            }
        });
 
        //根据url中是否出现过 "?" 来决定添加时间戳参数时使用 "?" 还是 "&" 
        var paramPrefix = url.indexOf("?") == -1 ? "?" : "&";
 
        url = url + paramPrefix + "jsonpCallback=" + "jsonpCallback_" + ff;
        var param = "";
 
        if (typeof params.data != "undefined" && params.data != null) {
         
            var data = params.data;
            for (var prop in data) {
                param += prop + "=" + data[prop] + "&";
            }
            param = param.substring(0, param.length - 1);
        }
        if (param.length > 0)
        url = url + "&" + param; 
        var script = document.createElement("script"); 
        document.body.appendChild(script); 
        script.src = url; 
        script.charset ="UTF-8";
        // for firefox, google etc.
        script.onerror = function() {
            if (typeof params.error != "undefined") {
                params.error();
            }
             
        }
        script.onload = function() {
 
        document.body.removeChild(script); 
        } 
        // for ie 
        script.onreadystatechange = function() { 
          if (this.readyState == "loaded" || this.readyState == "complete") { 
            document.body.removeChild(script);
          } 
        }
      }
    },
    getQueryString: function(name){
          var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
          var r = window.location.search.substr(1).match(reg);
          if(r!=null)return  unescape(r[2]); return null;
    },
    cookie: {
        get: function(_name) {
            var cookies = document.cookie,
                pos = cookies.indexOf(_name + '='),
                value;
            if (pos !== -1) {
                var start = pos + _name.length + 1;
                var end = cookies.indexOf(';', start);
                //最后一个
                if (end === -1) { end = cookies.length; }
                value = cookies.substring(start, end);
                value = decodeURIComponent(value);
            }
            return value;
        },
        set: function(_name, _value) {
            document.cookie = _name + '=' + encodeURIComponent(_value);
        },
        clearcookie: function(_name) {
            document.cookie = _name + "=;expires=" + (new Date(0)).toGMTString();
        }
    },
    session: {
        get: function(_name) {
            return window.sessionStorage.getItem(_name);
        },
        set: function(_name, _value) {
            window.sessionStorage.setItem(_name, _value);
        },
        remove: function(_name) {
            window.sessionStorage.removeItem(_name);
        },
        clear: function() {
            window.sessionStorage.clear();
        },
        getAll: function() {
            return window.sessionStorage;
        },
        isExist: function(_name) {
            if (window.sessionStorage.getItem(_name)) {
                return true;
            } else {
                return false;
            }
        }
    },
    localStorage: {
        get: function(_name) {
            return window.localStorage.getItem(_name);
        },
        set: function(_name, _value) {
            window.localStorage.setItem(_name, _value);
        },
        remove: function(_name) {
            window.localStorage.removeItem(_name);
        },
        clear: function() {
            window.localStorage.clear();
        },
        getAll: function() {
            return window.localStorage;
        },
        isExist: function(_name) {
            if (window.localStorage.getItem(_name)) {
                return true;
            } else {
                return false;
            }
        }
    },
    GetLength:function(str,type) {
        if(type){
            type=type
        }
        else
        {
            type=0
        }
        var realLength = 0, len =str.length, charCode = -1;
        for (var i = 0; i < len; i++) {
            charCode = str.charCodeAt(i);
            if(type==1){
                    if (charCode >= 0 && charCode <= 128) realLength += 0.5;
                        else 
                    { 
                      realLength += 1;
                    }
            }
            else
            {
                  if (charCode >= 0 && charCode <= 128) realLength += 1;
                    else 
                    { 
                      realLength += 1;
                    }
            }
        }
        return Math.round(realLength);
     },
    toastIt: function (text, timeout, options) {
        var timeout = timeout || 3000;
        let toast = document.createElement('div');
        toast.classList.add('toast-it');
        let content = document
            .createTextNode(text);
        toast.appendChild(content);
        toast.style.animationDuration = timeout / 1000 + 's';
        for (let prop in options) {
            toast.style[prop] = options[prop];
        }
        if (!document.querySelector(".toast-it")) {
            document.body.appendChild(toast);
            setTimeout(function () {
                document.body.removeChild(toast);
            }, timeout);
        }

    },
    loading:{
        show:function (text,timeout, options) {
        let loading = document.createElement('div');
        loading.classList.add('dz_loading');
        loading.appendChild('<img src="https://img.zhipin.com/s29/d4a126099ac8dbca8afac0c9de7563df_loading.gif"/>');
        for (let prop in options) {
            loading.style[prop] = options[prop];
        }
        if(!document.querySelector(".dz_loading")){
           document.body.appendChild(loading);
        }
       },
        hide:function(){
        document.body.removeChild(document.querySelector(".dz_loading"));
       }
    },
    form: {
        formser: function (form) {
            var form = document.getElementById(form);
            var arr = {};
            for (var i = 0; i < form.elements.length; i++) {
                var feled = form.elements[i];
                switch (feled.type) {
                    case undefined:
                    case 'button':
                    case 'file':
                    case 'reset':
                    case 'submit':
                        break;
                    case 'checkbox':
                    case 'radio':
                        if (!feled.checked) {
                            break;
                        }
                    default:
                        if (arr[feled.name]) {
                            arr[feled.name] = arr[feled.name] + ',' + feled.value;
                        } else {
                            arr[feled.name] = feled.value;

                        }
                }
            }
            return arr
        }
    },
    regexp: {
        "match": /^(.+?)(\d+)-(\d+)$/,
        "z": /[\w\W]+/,
        "*6-16": /^[\w\W]{6,16}$/,
        "n": /^$|^\d+$/,
        "n6-16": /^\d{6,16}$/,
        "s": /^[\u4E00-\u9FA5\uf900-\ufa2d\w\.\s]+$/,
        "s6-18": /^[\u4E00-\u9FA5\uf900-\ufa2d\w\.\s]{6,18}$/,
        "p": /^[0-9]{6}$/,
        "m": /^[1][3456789][0-9]{9}$/,
        "tel": /((^(0\d{2})-(\d{8})$)|(^(0\d{3})-(\d{7,8})$)|(^(0\d{2})-(\d{8})-(\d+)$)|(^(0\d{3})-(\d{7,8})-(\d+)$)|(^(0\d{2})(\d{8})$)|(^(0\d{3})(\d{7,8})$)|(^(0\d{2})(\d{8})-(\d+)$)|(^(0\d{3})(\d{7,8})-(\d+)$))|^[1][3456789][0-9]{9}$/,
        "e": /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
        "xz": /(^[1-9]\d{0,1}$)|(^[1-9]\d{1}[0]$)/,
        "id": /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X|x)$/,
        "url": /(http:\/\/|ftp:\/\/|https:\/\/|www)?[^\u4e00-\u9fa5\s\uFE30-\uFFA0]*?\.([a-zA-Z0-9]|[1-255])[^\u4e00-\u9fa5\s\uFE30-\uFFA0]*/
    }
    , expand: {
        
    },
    dateFormat: function (date, fmt="yyyy-MM-dd") { 
        var o = {
            "M+": date.getMonth() + 1,                 //月份   
            "d+": date.getDate(),                    //日   
            "h+": date.getHours(),                   //小时   
            "m+": date.getMinutes(),                 //分   
            "s+": date.getSeconds(),                 //秒   
            "q+": Math.floor((date.getMonth() + 3) / 3), //季度   
            "S": date.getMilliseconds()             //毫秒   
        };
        if (/(y+)/.test(fmt))
            fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt))
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    }
};
export default ZN;